package com.cu.employmentmanagementsystem.handler;

import com.cu.employmentmanagementsystem.common.enums.WxChatMsgTypeEnum;
import com.cu.employmentmanagementsystem.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReceiveTextMsgHandler implements WxChatMsgHandler
{
    @Resource
    private RedisUtil redisUtil;

    private static final String CODE_KEY_WORD = "验证码";
    private static final String LOGIN_CODE_PREFIX = "loginCode";
    @Override
    public WxChatMsgTypeEnum getChatMsgType()
    {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String,String> messageMap)
    {
        log.info("接收到文本消息");
        String fromUserName = messageMap.get("FromUserName");
        String content = messageMap.get("Content");
        if (content.contains(CODE_KEY_WORD))
        {
            //随机生成验证码
            int code = (int) (Math.random() * 10000);
            String key = redisUtil.buildKey(LOGIN_CODE_PREFIX,String.valueOf(code));
            redisUtil.setNx(key, fromUserName, 5L, TimeUnit.MINUTES);
            return "<xml>\n" +
                    "  <ToUserName><![CDATA["+ fromUserName +"]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA["+messageMap.get("ToUserName")+"]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[验证码：    "+code+" 5分钟内有效哦~]]></Content>\n" +
                    "</xml>";
        }
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA["+ fromUserName +"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+messageMap.get("ToUserName")+"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+ content +"]]></Content>\n" +
                "</xml>";
        return replyContent;
    }
}
